package com.zx.article.manager.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zx.article.manager.dao.IManagerDao;
import com.zx.article.manager.model.ManagerModel;
import com.zx.article.util.DBUtils;

public class ManagerDaoImpl implements IManagerDao {

	private DBUtils dbUtils = new DBUtils();

	private Map<String, String> getMap() {
		Map<String, String> map = new HashMap<>();
		map.put("account", "m_account");
		map.put("password", "m_password");
		map.put("realName", "m_real_name");
		map.put("nickName", "m_nick_name");
		map.put("image", "m_image");
		map.put("email", "m_email");
		return map;
	}

	@Override
	public ManagerModel queryModel(String account) {
		String sqlString = "SELECT m_account,m_password,m_real_name,m_nick_name,m_image,m_email FROM manager WHERE m_account = ? ";
		Object[] valObjects = { account };
		return dbUtils.queryOne(sqlString, valObjects, ManagerModel.class, getMap());
	}

	@Override
	public ManagerModel queryModel(ManagerModel managerModel) {
		StringBuffer sqlString = new StringBuffer(
				"SELECT m_account,m_password,m_real_name,m_nick_name,m_image,m_email FROM manager ");
		List<Object> appendWhere = appendWhere(sqlString, managerModel);
		return dbUtils.queryOne(sqlString.toString(), appendWhere.toArray(), ManagerModel.class, getMap());
	}

	@Override
	public String insertModel(ManagerModel managerModel) {
		String sqString = "INSERT INTO manager(m_account,m_password,m_nick_name) VALUES(?,?,?) ";
		Object[] valObjects = { managerModel.getAccount(), managerModel.getPassword(), managerModel.getNickName() };
		return dbUtils.update(sqString, valObjects);
	}

	private List<Object> appendWhere(StringBuffer sqlString, ManagerModel managerModel) {
		List<Object> list = new ArrayList<>();
		sqlString.append("where 1=1 ");
		String account = managerModel.getAccount();
		if (account != null && !account.isEmpty()) {
			sqlString.append("and m_account = ? ");
			list.add(account);
		}
		String password = managerModel.getPassword();
		if (password != null && !password.isEmpty()) {
			sqlString.append("and m_password = ? ");
			list.add(password);
		}
		return list;
	}

	@Override
	public String updata(ManagerModel managerModel) {
		String sqlString = "UPDATE manager SET m_nick_name = ? WHERE m_account = ? ";
		Object[] valObjects = { managerModel.getNickName(), managerModel.getAccount() };
		return dbUtils.update(sqlString, valObjects);
	}

}
